package com.small.nacos.common.task.engine;

import small.common.core.exceptions.Closeable;
import com.small.nacos.api.exception.NacosException;
import com.small.nacos.common.task.AbstractExecuteTask;
import com.small.nacos.common.task.NacosTask;
import com.small.nacos.common.task.NacosTaskProcessor;
import org.slf4j.Logger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author zhoujin
 * @Date 2022/11/13 13:55
 */
public class TaskExecuteWorker implements NacosTaskProcessor, Closeable {

    /**
     * 队列最大长度32746
     */
    private static final int QUEUE_CAPACITY = 1 << 15;

    private final BlockingQueue<Runnable> queue;

    private final Logger log;

    private final AtomicBoolean closed;

    private final String name;

    public TaskExecuteWorker(final String name, final int mod, final int total, final Logger logger) {
        this.name = name + "_" + mod + "%" + total;
        this.queue = new ArrayBlockingQueue<Runnable>(QUEUE_CAPACITY);
        this.closed = new AtomicBoolean(false);
        this.log = logger;
        new InnerWorker(name).start();
    }

    @Override
    public void shutdown() throws NacosException {
        queue.clear();
        closed.compareAndSet(false, true);
    }

    @Override
    public boolean process(NacosTask task) {
        if (task instanceof AbstractExecuteTask) {
            putTask((Runnable) task);
        }
        return true;
    }

    private void putTask(Runnable task) {
        try {
            queue.put(task);
        } catch (InterruptedException ire) {
            log.error(ire.toString(), ire);
        }
    }

    private class InnerWorker extends Thread {

        InnerWorker(String name) {
            setDaemon(false);
            setName(name);
        }

        @Override
        public void run() {
            while (!closed.get()) {
                try {
                    Runnable task = queue.take();
                    long begin = System.currentTimeMillis();
                    task.run();
                    long duration = System.currentTimeMillis() - begin;
                    if (duration > 1000L) {
                        log.warn("distro task {} takes {}ms", task, duration);
                    }
                } catch (Throwable e) {
                    log.error("[DISTRO-FAILED] " + e.toString(), e);
                }
            }
        }
    }
}
